<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/1 0001
 * Time: 17:50
 */

namespace app\api\controller\v1\cleaner;


use app\api\controller\v1\Cleaner;
use library\tools\Data;
use think\Db;
use think\exception\HttpResponseException;

class Withdrawal extends Cleaner
{
    /**
     * 查看提现记录
     */
    public function index()
    {
        $where = [['cid','eq',$this->cid]];
        $list = $this->_query('CleanerWithdrawal')->where($where)->order('create_at desc')->page(true,false,false,10);
        $this->success('获取提现记录成功！',$list);
    }

    /**
     * 申请提现
     */
    public function save()
    {
        $data = $this->_input([
            'amount' => $this->request->post('amount'),
            'bid' => $this->request->post('bid'),
            'sms_code' => $this->request->post('sms_code')
        ],[
            'amount' => '/^[0-9]+(.[0-9]{1,2})?$/',
            'bid' => 'require|number',
            'sms_code' => 'require|number'
        ]);
        //验证余额
        if($data['amount'] > $this->cleaner->balance)
        {
            $this->error('余额不足！');
        }
        //验证银行卡
        if(Db::name('CleanerBankCard')->where([['id','eq',$data['bid']],['cid','eq',$this->cid]])->count() < 1)
        {
            $this->error('银行卡信息查询失败！');
        }
        //验证手机验证码
        $cache = cache($cachekey = "send_register_sms_{$this->cleaner->phone}");
        if(!isset($cache['captcha']) || $cache['captcha'] != $data['sms_code']){
            $this->error('短信验证码错误！');
        }
        try {
            Db::transaction(function () use($data){
                // 提现写入
                Db::name('CleanerWithdrawal')->insert([
                    'cid' => $this->cid,
                    'amount' => $data['amount'],
                    'bid' => $data['bid'],
                ]);
                // 余额扣除
                Db::name('Cleaner')->where('id',$this->cid)->setDec('balance',$data['amount']);
                Db::name('CleanerBalanceLog')->insert([
                    'cid' => $this->cid,
                    'amount' => $data['amount'],
                    'content' => "申请提现暂时扣除{$data['amount']}元"
                ]);
            });
            $this->success('提现申请成功！', '');
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $e) {
            $this->error("提现申请失败，请稍候再试！{$e->getMessage()}");
        }
    }
}